/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controllers;

import com.configs.Config;
import com.helpers.Crypto;
import com.helpers.Validator;
import com.models.beans.UserSessionBean;
import com.models.entities.TblUser;
import java.io.IOException;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author HUYTQ
 */
@WebServlet(name = "UserServlet", urlPatterns = {"/User"})
public class UserServlet extends HttpServlet {

    @EJB
    private UserSessionBean userSessionBean;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null || action.equals("")) {
            action = "";
        }
        if (action.equals("LoginPage")) {
            request.getRequestDispatcher(Config.LOGIN_PAGE_JSP).forward(request, response);
            return;
        }///// ket thuc 
        /**
         * thuc hien action login va tra ve trang tuong ung
         */
        else if (action.equals("Login")) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            if (username == null || password == null) {
                request.setAttribute("LOGIN_FAIL", "Username or password wrong !!!");
                request.getRequestDispatcher(Config.LOGIN_PAGE_JSP).forward(request, response);
                return;
            }

            password = Crypto.encrypPassword(password);
            TblUser user = userSessionBean.checkLogin(username, password);
            if (user != null) {
                int status = user.getStatus();
                // status 0 : can login to system
                // otherwise : cannot
                if (status == 0) {
                    // lan dau tien dang nhap he thong
                    // tao session. gan true : neu ko ton tai. tao moi
                    HttpSession session = request.getSession(true);
                    session.setAttribute(Config.USER_SESSION_PARAM, user);
                    response.sendRedirect(Config.HOME_SERVLET);
                    
                    return;
                } else {
                    // 
                    request.setAttribute("MESSAGE_BANNED", user.getFullName());
                    request.getRequestDispatcher(Config.BANNED_PAGE_JSP).forward(request, response);
                    return;
                }
            } else {
                // wrong username or password
                request.setAttribute("LOGIN_FAIL", "Username or password wrong !!!");
                request.getRequestDispatcher(Config.LOGIN_PAGE_JSP).forward(request, response);
                return;
            }
        }///// ket thuc login action
        /**
         * thuc hien action logout, remove session USER
         */
        else if (action.equals("Logout")) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                response.sendRedirect("USER?action=LoginPage");
                return;
            }
            session.invalidate();
            // session.removeAttribute(Config.USER_SESSION_PARAM); --> should not
            response.sendRedirect(Config.HOME_SERVLET);
            return;
        }///// ket thuc logout
        /**
         * dan den trang register
         */
        else if (action.equals("RegisterPage")) {
            request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
            return;
        } //// ket thuc register 
        /**
         * thuc hien action register va dan den trang tuong ung
         */
        else if (action.equals("Register")) {
            boolean isValid = true;
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String confirm = request.getParameter("confirm");
            String email = request.getParameter("email");
            String fullName = request.getParameter("fullName");

            ////check null param
            if (username == null || password == null || confirm == null
                    || email == null || fullName == null) {
                request.setAttribute("MESSAGE_REGISTER_FAIL", "SORRY ^^");
                request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
                return;
            }

            /// kiem tra su ton tai cua username
            boolean isExist = userSessionBean.isExistsUsername(username);
            if (isExist) {
                isValid = false;
                request.setAttribute("MESSAGE_USER_FAIL", "Username was exist");
                request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
                return;
            }

            //// kiem tra khoang trang trong username
            if (!Validator.checkUsername(username)) {
                isValid = false;
                request.setAttribute("MESSAGE_USER_FAIL", "Username just include a-> z, 0 -> 9 and _ or .   !!!!");
                request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
                return;
            }

            ///// kiem tra password
            if (!Validator.checkPasswordCharacter(password)) {
                isValid = false;
                request.setAttribute("MESSAGE_PASSWORD_FAIL", "Password character must > 6 and < 30 !!!!");
            }

            ///// kiem tra confirm
            if (!password.equals(confirm)) {
                isValid = false;
                request.setAttribute("MESSAGE_CONFIRM_FAIL", "Confirm password wrong !!!!");
            }

            //// kiem tra email

            if (!Validator.checkEmailCharacter(email.trim())) {
                isValid = false;
                request.setAttribute("MESSAGE_EMAIL_FAIL", "Email character must < 200 and > 10 !!!!  ");
            } else if (!Validator.isValidEmailAddress(email.trim())) {
                isValid = false;
                request.setAttribute("MESSAGE_EMAIL_FAIL", "Email wrong schema !!!!");
            } else if (userSessionBean.isExistsEmail(email.trim())) {
                isValid = false;
                request.setAttribute("MESSAGE_EMAIL_FAIL", "Email was exits !!!!");
            }


            //// kiem tra full name

            if (!fullName.trim().equals("") && !Validator.checkFullName(fullName)) {
                isValid = false;
                request.setAttribute("MESSAGE_FULLNAME_FAIL", "Full name must < 100 and > 10 !!!!");
            }

            if (isValid) {
                password = Crypto.encrypPassword(password);
                TblUser user = new TblUser();
                // set parameters for User
                user.setUsername(username);
                user.setPassword(password);
                user.setEmail(email.trim());
                user.setFullName(fullName.trim());
                user.setRole(0);
                user.setRating(0);
                user.setUserLevel(0);
                user.setStatus(0);
                user.setCreateDate(new Date());

                isValid = userSessionBean.register(user);

                if (isValid) {
                    request.setAttribute("MESSAGE_REGISTER_SUCCESS", "REGISTER SUCCESS");
                    request.getRequestDispatcher(Config.REGISTER_SUCCESS_PAGE_JSP).forward(request, response);
                    return;
                } else {
                    request.setAttribute("MESSAGE_REGISTER_FAIL", "SORRY ^^");
                    request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
                    return;
                }
            } else {
                request.getRequestDispatcher(Config.REGISTER_PAGE_JSP).forward(request, response);
                return;
            }
        } //////ket thuc
        /**
         * dan den profile page
         */
        else if (action.equals("ProfilePage")) {
            request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
        }///// ket thuc ProfilePage
        /**
         * thuc hien update profile
         */
        else if (action.equals("Change Profile")) {
            //// lay session va user dang hien hanh
            /// kiem tra xem session co null ko
            /// kiem tra user co null ko
            HttpSession session = request.getSession(false);
            if (session == null) {
                response.sendRedirect("USER?action=LoginPage");
                return;
            }
            TblUser user = (TblUser) session.getAttribute(Config.USER_SESSION_PARAM);
            if (user == null) {
                response.sendRedirect("USER?action=LoginPage");
                return;
            }

            ///// lay param email va fullName
            String email = request.getParameter("email");
            String fullName = request.getParameter("fullName");

            if (email == null || fullName == null) {
                request.setAttribute("MESSAGE_UPDATE", "Sorry, something wrong !!!");
                request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
                return;
            }
            boolean isValid = true;
            //// kiem tra email
            if (!Validator.checkEmailCharacter(email.trim())) {
                isValid = false;
                request.setAttribute("MESSAGE_EMAIL_FAIL", "Email character must < 200 and > 10 !!!!  ");
            } else if (!Validator.isValidEmailAddress(email.trim())) {
                isValid = false;
                request.setAttribute("MESSAGE_EMAIL_FAIL", "Email wrong schema !!!!");
            } else if (!user.getEmail().equals(email.trim())) {
                if (userSessionBean.isExistsEmail(email.trim())) {
                    isValid = false;
                    request.setAttribute("MESSAGE_EMAIL_FAIL", "Email was exits !!!!");
                }
            }
            //// kiem tra full name

            if (!fullName.trim().equals("") && !Validator.checkFullName(fullName)) {
                isValid = false;
                request.setAttribute("MESSAGE_FULLNAME_FAIL", "Full name must < 100 and > 10 !!!!");
            }

            ///// thuc hien update neu tmp = true
            if (isValid) {
                user.setFullName(fullName);
                user.setEmail(email);
                isValid = userSessionBean.updateProfile(user);
                if (isValid) {
                    session.setAttribute(Config.USER_SESSION_PARAM, user);
                    request.setAttribute("MESSAGE_UPDATE", "Update profile successful ^^");
                } else {
                    request.setAttribute("MESSAGE_UPDATE", "Sorry, something wrong !!!");
                }
            }
            request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
            return;
        }////// ket thuc
        /**
         * thuc hien thay doi password
         */
        else if (action.equals("Change Password")) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                response.sendRedirect("USER?action=LoginPage");
                return;
            }
            TblUser user = (TblUser) session.getAttribute(Config.USER_SESSION_PARAM);
            if (user == null) {
                response.sendRedirect("USER?action=LoginPage");
                return;
            }
            boolean isValid = true;
            String current = request.getParameter("current");
            String confirm = request.getParameter("confirm");
            String password = request.getParameter("password");

            if (current == null || confirm == null || password == null) {
                request.setAttribute("MESSAGE_UPDATE", "Sorry, something wrong !!!");
                request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
                return;
            }

            current = Crypto.encrypPassword(current);
            //// kiem tra current password
            if (!user.getPassword().equals(current)) {
                isValid = false;
                request.setAttribute("MESSAGE_CURRENT_PASSWORD_FAIL", "Current Password fail !!!!!");
                request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
                return;
            }//// ket thuc


            ///// kiem tra password
            if (!Validator.checkPasswordCharacter(password)) {
                isValid = false;
                request.setAttribute("MESSAGE_PASSWORD_FAIL", "Password character must > 6 and < 30 !!!!");
            }

            ///// kiem tra confirm
            if (!password.equals(confirm)) {
                isValid = false;
                request.setAttribute("MESSAGE_CONFIRM_FAIL", "Confirm password wrong !!!!");
            }

            //// thuc hien change password neu isValid = true
            if (isValid) {
                password = Crypto.encrypPassword(password);
                isValid = userSessionBean.updatePassword(user.getUserId(), password);
                if (isValid) {
                    user.setPassword(password);
                    session.setAttribute(Config.USER_SESSION_PARAM, user);
                    request.setAttribute("MESSAGE_UPDATE", "Change password successful ^^");
                } else {
                    request.setAttribute("MESSAGE_UPDATE", "Sorry, something wrong !!!");
                }
            }
            request.getRequestDispatcher(Config.PROFILE_PAGE_JSP).forward(request, response);
            return;
        }//// ket thuc
        /**
         * thuc hien khi action = ""
         */
        else if (action.equals("")) {
            response.sendRedirect("Home");
            return;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
